//
//  AddressSelectView.m
//  yiluServe
//
//  Created by 杨阳 on 2017/9/20.
//  Copyright © 2017年 jian wang. All rights reserved.
//

#import "AddressSelectView.h"
#import "LabelTableViewCell.h"
#import "ProvinceModel.h"
#import "MBProgressHUD.h"

@interface AddressSelectView()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UIView * backView;

@property (nonatomic,strong) UIScrollView * scrollVoew;

@property (nonatomic,strong) UITableView * leftTableView, *midTableView,*rightTableView;

@property (nonatomic,strong) UILabel * leftlabel , * midlabel , * rightlabel;

@property (nonatomic,strong) UIView * redLineView , * lineView;

@property (nonatomic) TitleLableStay leftStay , midStay , rightStay;

@property (nonatomic,strong) UILabel * titleLable;

@property (nonatomic) NSInteger leftNum,midNum,rightNum;

@property (nonatomic,strong) ProvinceModel * model;

@end

#define TopSpace 260*PROPORTION_WIDTH_IPHONE6
#define LeftTableTag 10000
#define MidTableTag 10001
#define RightTableTag 10002
#define LeftTableID @"lefttalbeViewID"
#define MidTableID @"midtalbeViewID"
#define RightTableID @"righttalbeViewID"

@implementation AddressSelectView

-(instancetype)initWithFrame:(CGRect)frame{

    if (self = [super initWithFrame:frame]) {
        [self layoutUI];
        [self getData];
        self.backgroundColor = RGBColor1(0, 0, 0, 0.7);
    }
    return self;
}

-(void)getData{

    [self showLoading];
    [[QYNetManager sharedManager]POST:kGetCitys parameters:nil andApiTyp:SsehApiTypMain SuccessBlock:^(id responseObject) {
        [self hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            self.model = [ProvinceModel yy_modelWithDictionary:responseObject];
            [self.leftTableView reloadData];
            [UIView animateWithDuration:0.5 animations:^{
                self.backView.frame = CGRectMake(0, TopSpace, VIEW_WIDTH, VIEW_HEIGHT-TopSpace);
            } completion:^(BOOL finished) {
            }];
        }else{
            [self showErrorTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:SsehPoolNetStr];
    }];
    
}


-(void)layoutUI{

    __weak typeof (self)weakSelf = self;
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, VIEW_HEIGHT, VIEW_WIDTH, VIEW_HEIGHT-TopSpace)];
    _backView.backgroundColor = [UIColor backGroudColorForView];
    [self addSubview:_backView];
//titleLable
    _titleLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 40)];
    _titleLable.textColor = [UIColor textLightGrayColor];
    _titleLable.font = [UIFont systemFontOfSize:17];
    _titleLable.text = @"选择省";
    _titleLable.textAlignment = NSTextAlignmentCenter;
    [_backView addSubview:_titleLable];
    
//cancel button
    
    UIView * cancleView = [UIView new];
    cancleView.backgroundColor = [UIColor backGroudColorForView];
    [_backView addSubview:cancleView];
    [_backView bringSubviewToFront:cancleView];
    [cancleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.backView.mas_top);
        make.right.equalTo(weakSelf.backView.mas_right);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
    UITapGestureRecognizer * cancleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancleClick)];
    [cancleView addGestureRecognizer:cancleTap];
    
    UIButton * closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn setTitle:@"╳" forState:UIControlStateNormal];
    [closeBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(cancleClick) forControlEvents:UIControlEventTouchUpInside];
    closeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [cancleView addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(5, 5, 5, 5));
    }];
    
    
// labelView
    UIView * labelnView = [[UIView alloc]initWithFrame:CGRectMake(0, 40, VIEW_WIDTH, 40)];;
    labelnView.backgroundColor = [UIColor whiteColor];
    [_backView addSubview:labelnView];
 
// leftLabel
    
    _leftlabel = [UILabel new];
    _leftlabel.textAlignment = NSTextAlignmentLeft;
    _leftlabel.textColor = [UIColor textLightGrayColor];
    _leftlabel.text = @"请选择";
    _leftlabel.font = [UIFont systemFontOfSize:14];
    _leftlabel.userInteractionEnabled = YES;
    [labelnView addSubview:_leftlabel];
    [_leftlabel mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.equalTo(labelnView.mas_left).offset(20);
        make.top.equalTo(labelnView.mas_top);
        make.bottom.equalTo(labelnView.mas_bottom).offset(-1);
        //make.width.mas_equalTo(70);
    }];
    
    UITapGestureRecognizer * tapLeft = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapLeftClick)];
    [_leftlabel addGestureRecognizer:tapLeft];
    
//midLabel
    _midlabel = [UILabel new];
    _midlabel.textAlignment = NSTextAlignmentLeft;
    _midlabel.textColor = [UIColor textLightGrayColor];
    _midlabel.text = @"请选择";
    _midlabel.font = [UIFont systemFontOfSize:14];
    _midlabel.userInteractionEnabled = YES;
    [labelnView addSubview:_midlabel];
    [_midlabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(weakSelf.leftlabel.mas_right).offset(10);
        make.top.equalTo(labelnView.mas_top);
        make.bottom.equalTo(labelnView.mas_bottom).offset(-1);
        //make.width.mas_equalTo(70);
    }];
    UITapGestureRecognizer * tapMid = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapMidClick)];
    [_midlabel addGestureRecognizer:tapMid];
//rightLabel
    _rightlabel = [UILabel new];
    _rightlabel.textAlignment = NSTextAlignmentLeft;
    _rightlabel.textColor = [UIColor textLightGrayColor];
    _rightlabel.text = @"请选择";
    _rightlabel.font = [UIFont systemFontOfSize:14];
    _rightlabel.userInteractionEnabled = YES;
    [labelnView addSubview:_rightlabel];
    [_rightlabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(weakSelf.midlabel.mas_right).offset(10);
        make.top.equalTo(labelnView.mas_top);
        make.bottom.equalTo(labelnView.mas_bottom).offset(-1);
        //make.width.mas_equalTo(70);
    }];
    
    UITapGestureRecognizer * tapRight = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapRightClick)];
    [_rightlabel addGestureRecognizer:tapRight];
    
// lineView
    _lineView = [UIView new];
    _lineView.backgroundColor = RGBColor(238, 238, 238);
    [labelnView addSubview:_lineView];
    [_lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(labelnView.mas_bottom);
        make.left.equalTo(labelnView.mas_left);
        make.right.equalTo(labelnView.mas_right);
        make.height.mas_equalTo(1);
    }];
  
    _redLineView = [UIView new];
    _redLineView.backgroundColor = [UIColor redColor];
    [_lineView addSubview:_redLineView];
    [_redLineView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.centerX.equalTo(weakSelf.leftlabel.mas_centerX);
        make.top.equalTo(weakSelf.lineView.mas_top);
        make.height.mas_equalTo(1);
        make.width.mas_equalTo(40);
    }];
    
// scrollview
    _scrollVoew = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 80, VIEW_WIDTH, VIEW_HEIGHT-TopSpace-80)];
    _scrollVoew.delegate = self;
    _scrollVoew.contentSize = CGSizeMake(VIEW_WIDTH * 3, VIEW_HEIGHT-TopSpace-80);
    _scrollVoew.pagingEnabled = YES;
    _scrollVoew.backgroundColor = [UIColor redColor];
    _scrollVoew.showsVerticalScrollIndicator = NO;
    _scrollVoew.showsHorizontalScrollIndicator = NO;
    _scrollVoew.bounces = NO;
    [_backView addSubview:_scrollVoew];
 
//lefttableView
    _leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, VIEW_WIDTH, VIEW_HEIGHT-TopSpace-80)];
    _leftTableView.delegate = self;
    _leftTableView.dataSource = self;
    _leftTableView.tag = LeftTableTag;
    _leftTableView.scrollsToTop = NO;
    _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _leftTableView.backgroundColor = [UIColor whiteColor];
    [_leftTableView registerNib:[UINib nibWithNibName:@"LabelTableViewCell" bundle:nil] forCellReuseIdentifier:LeftTableID];
    [_scrollVoew addSubview:_leftTableView];
    
//midLeftTabelView
    _midTableView = [[UITableView alloc]initWithFrame:CGRectMake(VIEW_WIDTH,0, VIEW_WIDTH, VIEW_HEIGHT-TopSpace-80)];
    _midTableView.delegate = self;
    _midTableView.dataSource = self;
    _midTableView.scrollsToTop = NO;
    _midTableView.tag = MidTableTag;
    _midTableView.backgroundColor = [UIColor whiteColor];
    _midTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_midTableView registerNib:[UINib nibWithNibName:@"LabelTableViewCell" bundle:nil] forCellReuseIdentifier:MidTableID];
    [_scrollVoew addSubview:_midTableView];
    
//rightTableView
    _rightTableView = [[UITableView alloc]initWithFrame:CGRectMake(VIEW_WIDTH*2,0, VIEW_WIDTH, VIEW_HEIGHT-TopSpace-80)];
    _rightTableView.delegate = self;
    _rightTableView.dataSource = self;
    _rightTableView.tag = RightTableTag;
    _rightTableView.backgroundColor = [UIColor whiteColor];
    _rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_rightTableView registerNib:[UINib nibWithNibName:@"LabelTableViewCell" bundle:nil] forCellReuseIdentifier:RightTableID];
    [_scrollVoew addSubview:_rightTableView];
    
    
    _leftStay = SelectSaty;
    _midStay = HidenStay;
    _rightStay = HidenStay;
    [self updataLabelStay];
    
}

-(void)tapLeftClick{
    __weak typeof (self)weakSelf = self;
    [_scrollVoew setContentOffset:CGPointMake(0, 0) animated:YES];
    [_redLineView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.leftlabel.mas_centerX);
        make.top.equalTo(weakSelf.lineView.mas_top);
        make.height.mas_equalTo(1);
        make.width.mas_equalTo(40);
    }];
}

-(void)tapMidClick{
    __weak typeof (self)weakSelf = self;
    [_scrollVoew setContentOffset:CGPointMake(VIEW_WIDTH, 0) animated:YES];
    [_redLineView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.midlabel.mas_centerX);
        make.top.equalTo(weakSelf.lineView.mas_top);
        make.height.mas_equalTo(1);
        make.width.mas_equalTo(40);
    }];
}

-(void)tapRightClick{
    __weak typeof (self)weakSelf = self;
    [_scrollVoew setContentOffset:CGPointMake(VIEW_WIDTH*2, 0) animated:YES];
    [_redLineView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.rightlabel.mas_centerX);
        make.top.equalTo(weakSelf.lineView.mas_top);
        make.height.mas_equalTo(1);
        make.width.mas_equalTo(40);
    }];
}

-(void)cancleClick{
    
    [self dismissContactView];
    
}

-(void)updataLabelStay{

    switch (_leftStay) {
        case SelectSaty:
            _leftlabel.text = @"请选择";
            _leftlabel.textColor = [UIColor redColor];
            break;
        case HidenStay:
            
            break;
        case ShowStay:
            //_leftlabel.text = @"上海市";
            break;
            
        default:
            break;
    }
    
    switch (_midStay) {
        case SelectSaty:
            _midlabel.text = @"请选择";
            _midlabel.textColor = [UIColor redColor];
            break;
        case HidenStay:
            _midlabel.text = @" ";
            break;
        case ShowStay:
            //_midlabel.text = @"上海市";
            break;
            
        default:
            break;
    }
    
    switch (_rightStay) {
        case SelectSaty:
            _rightlabel.text = @"请选择";
            _rightlabel.textColor = [UIColor redColor];
            break;
        case HidenStay:
            _rightlabel.text = @"";
            break;
        case ShowStay:
            //_rightlabel.text = @"上海市";
            break;
            
        default:
            break;
    }
}

#pragma mark - tableView  代理

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == LeftTableTag) {
        return self.model.data.count;
    }    else if(tableView.tag == MidTableTag){
        return self.model.data[self.leftNum].cityBeans.count;
    }else if(tableView.tag == RightTableTag){
        return self.model.data[self.leftNum].cityBeans[self.midNum].cityBeans.count;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 35;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak typeof (self)weakSelf = self;
    if (tableView.tag == LeftTableTag) {
        ProvinceBeans * pModel = self.model.data[indexPath.row];
        if (![pModel.name isEqualToString:_leftlabel.text]) {
            _leftlabel.text = pModel.name;
            _leftlabel.textColor = [UIColor textLightGrayColor];;
            _leftStay = ShowStay;
            _midStay= SelectSaty;
            _rightStay = HidenStay;
            [self.scrollVoew setContentOffset:CGPointMake(VIEW_WIDTH, 0) animated:YES];
            _redLineView.hidden = NO;
            [_redLineView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(weakSelf.midlabel.mas_centerX);
                make.top.equalTo(weakSelf.lineView.mas_top);
                make.height.mas_equalTo(1);
                make.width.mas_equalTo(40);
            }];

            _leftNum = indexPath.row;
            [self.midTableView reloadData];
        }

    }else if(tableView.tag == MidTableTag){
        CityBeans * cityModel = self.model.data[self.leftNum].cityBeans[indexPath.row];
        if (![cityModel.name isEqualToString:_midlabel.text]) {
            _midlabel.text = cityModel.name;
            _midlabel.textColor = [UIColor textLightGrayColor];
            
            _midStay = ShowStay;
            _rightStay = SelectSaty;
            [self.scrollVoew setContentOffset:CGPointMake(VIEW_WIDTH*2, 0) animated:YES];
            _redLineView.hidden = NO;
            [_redLineView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(weakSelf.rightlabel.mas_centerX);
                make.top.equalTo(weakSelf.lineView.mas_top);
                make.height.mas_equalTo(1);
                make.width.mas_equalTo(40);
            }];

            _midNum = indexPath.row;
            [self.rightTableView reloadData];

        }
    }else if(tableView.tag == RightTableTag){
        DistrictBeans * districtModel = self.model.data[self.leftNum].cityBeans[self.midNum].cityBeans[indexPath.row];
        if (![districtModel.name isEqualToString:_rightlabel.text]) {
            _rightlabel.text = districtModel.name;
            _rightlabel.textColor = [UIColor textLightGrayColor];
            _rightStay = ShowStay;
            _rightNum = indexPath.row;

            ProvinceBeans * pModel = self.model.data[self.leftNum];
            CityBeans * cityModel = self.model.data[self.leftNum].cityBeans[self.midNum];
            NSDictionary * dic = @{@"left":pModel.name,@"mid":cityModel.name,@"right":districtModel.name};
            if (_completeHandle) {
                _completeHandle(dic);
            }
            [self dismissContactView];
        }
    }
    [self updataLabelStay];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (tableView.tag == LeftTableTag) {
        LabelTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:LeftTableID];
        ProvinceBeans * pModel = self.model.data[indexPath.row];
        cell.nameLabel.text = pModel.name;
        return cell;
    }else if (tableView.tag == MidTableTag){
        LabelTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:MidTableID];
        CityBeans * cityModel = self.model.data[self.leftNum].cityBeans[indexPath.row];
        cell.nameLabel.text = cityModel.name;
        return cell;

    }else{
        LabelTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:RightTableID];
        DistrictBeans * districtModel = self.model.data[self.leftNum].cityBeans[self.midNum].cityBeans[indexPath.row];
        cell.nameLabel.text = districtModel.name;
        return cell;

    }
    return nil;
    
}

#pragma mark - scrollView 代理
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    CGFloat x = scrollView.contentOffset.x;
    
    if (x >= 0 && x < VIEW_WIDTH) {
        self.titleLable.text = @"选择省";
    }else if (x >= VIEW_WIDTH && x<VIEW_WIDTH*2){
        self.titleLable.text = @"选择市";
    }else{
        self.titleLable.text = @"选择区";
    }
    
    if (_leftStay == SelectSaty) {
        if (x > 0) {
            scrollView.scrollEnabled = NO;
            return;
        }
        return;
    }
    if (_midStay == SelectSaty) {
        if (x > VIEW_WIDTH) {
            scrollView.scrollEnabled = NO;
            return;
        }
    }
    scrollView.scrollEnabled = YES;
    
}

-(void)showView{
    
    if (self.alpha == 0) {
        [UIView animateWithDuration:0.5 animations:^{
            self.backView.frame = CGRectMake(0, TopSpace, VIEW_WIDTH, VIEW_HEIGHT-TopSpace);
            self.alpha = 1;
        } completion:^(BOOL finished) {
            
        }];
    }
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    [window addSubview:self];
    
}

-(void)dismissContactView
{
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.alpha = 0;
        self.backView.frame = CGRectMake(0, VIEW_HEIGHT, VIEW_WIDTH, VIEW_HEIGHT-TopSpace);
    } completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
    }];
    
}

- (void)showLoading {
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.label.text = @"正在努力加载...";
    hud.contentColor = [UIColor whiteColor];
    hud.bezelView.backgroundColor = [UIColor blackColor];
    [self addSubview:hud];
    [hud showAnimated:YES];
}

- (void)showErrorTipWithTitle:(NSString*)title {
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.label.text = title;
    hud.contentColor = [UIColor whiteColor];
    hud.customView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"closeNet"]];
    hud.bezelView.backgroundColor = [UIColor blackColor];
    [self addSubview:hud];
    [hud showAnimated:YES];
    
}

- (void)hideLoading {
    [MBProgressHUD hideHUDForView:self animated:YES];
}


@end





